<script setup>
import { routes } from './router/index.js'
import { useRouter } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'

const router = useRouter()
const showBack = ref(false)
const scrollTop = ref('')

const navigatePage = (page) => {
  router.push({
    path: page
  })
}

onMounted(() => {
  window.addEventListener("scroll", handleScroll, true);
})

onUnmounted(() => {
  window.addEventListener("scroll", handleScroll, true);
})

const handleScroll = () => {
  scrollTop.value = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop.value > 100) {
    showBack.value = true;
  } else {
    showBack.value = false;
  }
}

const scrollToTop = () => {
  let timer = null;
  //动画，使用requestAnimationFrame代替setInterval
  cancelAnimationFrame(timer);
  const intvl = scrollTop.value / 30
  timer = requestAnimationFrame(function fn() {
    if (scrollTop.value > 0) {
      scrollTop.value -= intvl;
      window.scrollTo(0, scrollTop.value)
      timer = requestAnimationFrame(fn);
    } else {
      cancelAnimationFrame(timer);
      showBack.value = false;
    }
  });
}
</script>

<template>
  <main>
    <router-view></router-view>
    <div class="float-menu">
      <div class="menu-item" v-for="item in routes" @click="navigatePage(item.path)">
        {{ item.name }}
      </div>
    </div>
    <div v-show="showBack" class="back-top" @click="scrollToTop">回到<br/>顶部</div>
  </main>
</template>

<style scoped>
main {
  padding: 0px;
  margin: 0px;
}
.back-top {
  position: fixed;
  right: 10px;
  bottom: 50px;
  border-radius: 50%;
  padding: 10px 20px;
  background:#333;
  color: #fff;
  z-index: 3;
  cursor: pointer;
}
.float-menu {
  position: fixed;
  left: -35px;
  background: gray;
  color: #fff;
  padding: 20px;
  border-radius: 8px;
  top: 50%;
  transform: translateY(-50%);
  transition: left 1s;
}
.menu-item {
  text-align: center;
  cursor: pointer;
}
.float-menu:hover {
  left: 0px;
}
</style>
